#include "TestEngine.h"
#include <chrono>
#include <cstdint>
#include <numeric>
#include <thread>
#include "DateTime.h"
#include "Logger.h"

using namespace std::placeholders;
using namespace xncc::user;
using namespace xncc::types;

TestEngine::TestEngine() : EventEngine(1)
{
}

void TestEngine::init()
{
    xncc::types::timer_id_t id1 = runAtOnce("2021-09-23_21:39:00.123", std::bind(&TestEngine::printTimeNow, this));
    if (id1 == INVALID_TIMER_ID) {
        LOG_ERROR(CONSOLE_LOG) << "create timer faild";
    }

    xncc::types::timer_id_t id2 =
        setTimerFunc(DateTime::timeMicro(), 1000, std::bind(&TestEngine::printTimer2Now, this));
    if (id2 == INVALID_TIMER_ID) {
        LOG_ERROR(CONSOLE_LOG) << "create timer 2 faild";
    }
    timerList.push_back(id2);
    LOG_INFO(CONSOLE_LOG) << "add time " << timerList[0] << "to  list";
}

void TestEngine::printTimeNow()
{
    int64_t now = DateTime::timeMicro();
    LOG_INFO(CONSOLE_LOG) << "time now is " << now << "cancel timer " << timerList[0];
    cancelTimer(timerList[0]);
}

void TestEngine::printTimer2Now()
{
    static int i = 1;
    while (i < 100000) {
        i++;
        int64_t now   = DateTime::timeMicro();
        auto    start = std::chrono::system_clock::now();
        LOG_INFO(TIMER_LOG) << ("timer id ") << timerList[0] << " time now is " << now << " index = " << i;
        auto end = std::chrono::system_clock::now();
        costs_.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count());
        if (i % 10000 == 0) {
            int64_t sum = std::accumulate(costs_.begin(), costs_.end(), 0);
            printf("average = %ld\n", (sum) / static_cast<int64_t>(costs_.size()));
            costs_.clear();
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
}